package com.cbb.admin.cbb;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.cbb.net.Constant;
import com.cbb.utils.ToastUtils;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class CheckStandActivity extends BaseActivity {
    //微信支付
    //  final protected IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
    final protected IWXAPI msgApi = WXAPIFactory.createWXAPI(this, Constant.WX_APP_ID,false);
    // final protected IWXAPI msgApi = WXAPIFactory.createWXAPI(CheckStandActivity.this, null);

    protected PayReq req;
    protected Map<String, String> resultunifiedorder;
    protected StringBuffer sb;
    public static final String WX_PAY = "weixin_pay";

    private static final int SDK_PAY_FLAG = 1;
    private PaymentBroadCastReceive receive;
    private StringRequest stringRequest , yuerStringRequest, wxStringRequest, caimiStringRequest;
    private Gson gson;
    private RequestQueue requestQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_stand);
        //init();
        //微信支付相关
        req = new PayReq();
        sb = new StringBuffer();
        msgApi.registerApp("wxd1b0a49fdff94083");
        requestQueue = Volley.newRequestQueue(this);
        registBroadCast();
    }

    private void registBroadCast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WX_PAY);
        receive = new PaymentBroadCastReceive();
        registerReceiver(receive, filter);
    }

    //接受微信的广播
    class PaymentBroadCastReceive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getBooleanExtra("is_pay", false)) {
                //mySendBroadcast(PAY_RESULT_SUCCESS);
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        Intent intent = new Intent(CheckStandActivity.this,
                                MainActivity.class);
                        intent.putExtra("selectPager", 1);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                }, 1500);
                ToastUtils.show(mContext,"支付成功！");
            } else {
                ToastUtils.show(mContext,"支付失败！");
            }
        }
    }

    /**
     * 微信支付
     */
    private void doWxPay(){
        wxStringRequest = new StringRequest(Request.Method.POST,
                "" + "/app/" + "order/payment/byWx", new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.v("返回结果", s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    int status = jsonObject.getInt("status");
                    int bizStatus = jsonObject.getInt("bizStatus");
                    if (status == 0 && bizStatus == 0) {
                        String data = jsonObject.getString("data");
                        JSONObject jsonData = new JSONObject(data);

                        req.appId = jsonData.getString("appid");
                        req.nonceStr = jsonData.getString("noncestr");
                        req.packageValue = jsonData.getString("package");
                        req.partnerId = jsonData.getString("partnerid");
                        req.prepayId = jsonData.getString("prepayid");
                        req.sign = jsonData.getString("sign");
                        req.timeStamp = jsonData.getString("timestamp");
/*
                        Runnable payRunnable = new Runnable() {
                            @Override
                            public void run() {
                                // 构造PayTask 对象
                                PayTask alipay = new PayTask(CheckStandActivity.this);
                                // 调用支付接口，获取支付结果
                                String result = alipay.pay(sign1, true);

                                Message msg = new Message();
                                msg.what = SDK_PAY_FLAG;
                                msg.obj = result;
                                mHandler.sendMessage(msg);
                            }
                        };

                        // 必须异步调用
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();*/

                        // 调微信支付
                        if(msgApi.isWXAppInstalled()&&msgApi.isWXAppSupportAPI()){
                            msgApi.sendReq(req);
                        }else{
                            ToastUtils.show(CheckStandActivity.this,"未安装微信,请修改支付方式或安装微信！");
                           /* builder = new AlertDialog.Builder(CheckStandActivity.this);
                            builder.setNeutralButton("关闭",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            mDialog.dismiss();
                                        }
                                    }).setTitle("友情提醒").setMessage("请安装微信客户端");

                            mDialog = builder.create();
                            mDialog.show();*/
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtils.show(CheckStandActivity.this, "主人，网络出错啦！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
            /*    map.put("orderCode", orderCode);
                map.put("token", token);*/
                return map;
            }
        };
        requestQueue.add(wxStringRequest);
    }
}
